const { network, ethers } = require("hardhat")
const { devlopmentChains, chainConfig } = require("../helper-hardhat-config")
const {
    storeImages,
    storeTokenUriMetadata,
} = require("../utils/uploadTopinata")
const { verifyContract } = require("../utils/verify")
const fs = require("fs")
const metadataTemplate = {
    name: "",
    description: "",
    image: "",
    attributes: [{ trait_type: "photo", value: 100 }],
}
let tokenUris = [
    "ipfs://QmNW2V2Cc9PvHcrGsdANyESiDKXKBCWSeNhnxmREn8TCDf",
    "ipfs://QmWiP9iAPrhMwQbCP2dyE45AbbmzBLKUDhiWPTQB5ib9dK",
    "ipfs://QmRmzM8ABwWVXWMJiUfuDQZA1c96N6QQ7Frtuh5Wboat4w",
]
const imagesLocation = "./images/Random/"

module.exports = async ({ getNamedAccounts, deployments }) => {
    //获取部署合约的地址(注意！使用hardhat网络部署合约时,如果config.js配置了namedAccounts:属性那么 getNamedAccounts()方法将返回多个参数 返回值必须加{})
    const { deployer } = await getNamedAccounts()
    const { deploy, log } = deployments

    if (process.env.UPLOAD_TO_PINATA == "true") {
        tokenUris = await hadleTokenUris()
    }

    let VRFCoordinatorV2MockAddress, SubscriptId, VRFCoordinatorV2Mock
    if (devlopmentChains.includes(network.name)) {
        VRFCoordinatorV2Mock = await ethers.getContract("VRFCoordinatorV2Mock")
        //本地mockVRF地址和subid
        VRFCoordinatorV2MockAddress = VRFCoordinatorV2Mock.address

        //创建Mock VRFSubscriptionID
        const tx = await (
            await VRFCoordinatorV2Mock.createSubscription()
        ).wait(1)
        SubscriptId = tx.events[0].args.subId
        //向订阅账户充值link
        await VRFCoordinatorV2Mock.fundSubscription(
            SubscriptId,
            ethers.utils.parseEther("10")
        )
    } else {
        VRFCoordinatorV2MockAddress =
            chainConfig[network.config.chainId].VrfFeedAddress
        SubscriptId = chainConfig[network.config.chainId].subscriptionId
    }

    log("deploying RandomIpfsNFT ...")
    const args = [
        VRFCoordinatorV2MockAddress,
        chainConfig[network.config.chainId].gasLimit,
        SubscriptId,
        chainConfig[network.config.chainId].callbackGasLimit,
        tokenUris,
        chainConfig[network.config.chainId].mintFeed,
    ]

    const randomIpfsNFT = await deploy("RandomIpfsNFT", {
        from: deployer,
        args: args,
        log: true,
        // @ts-ignore
        waitConfirmations: network.config.blockConfirmations || 1,
    })
    //本地链测试手动添加VRF服务消费者(所需要服务的合约地址)
    if (devlopmentChains.includes(network.name)) {
        // @ts-ignore
        await VRFCoordinatorV2Mock.addConsumer(
            SubscriptId.toNumber(),
            randomIpfsNFT.address
        )
    }
    console.log(" RandomIpfsNFT deployed")
    console.log("--------------------------")

    //校验合约代码
    if (
        !devlopmentChains.includes(network.name) &&
        process.env.ETHERSCAN_API_KEY
    ) {
        console.log("verifying contract")
        await verifyContract(randomIpfsNFT.address, args)
    }
}
async function hadleTokenUris() {
    tokenUris = []
    const { responses: uploadResponse, imageFile } = await storeImages(
        imagesLocation
    )
    console.log("tokenUri uploading")
    for (const Index in uploadResponse) {
        let tokenUriMetadata = { ...metadataTemplate }
        //构建metadata数据
        tokenUriMetadata.name = imageFile[Index].replace(".jpg", "")
        tokenUriMetadata.description = `perfer photo ${imageFile[Index]}`
        tokenUriMetadata.image = `ipfs://${uploadResponse[Index].IpfsHash}`
        console.log(`uploading ${tokenUriMetadata.name}...`)

        //循环上传metadata
        const metaDataUploadResponse = await storeTokenUriMetadata(
            tokenUriMetadata
        )
        tokenUris.push(`ipfs://${metaDataUploadResponse.IpfsHash}`)
    }

    console.log("token uri uploaded")
    console.log(tokenUris)
    fs.writeFileSync("../helper-hardhat-config.js", tokenUris.toString())
    return tokenUris
}

module.exports.tags = ["all", "randomipfs"]
